package com.xixi.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;

@Component
public class JwtTokenUtil {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    private SecretKey getSigningKey() {
        // 确保密钥长度足够（至少32字符）
        if (secret.length() < 32) {
            throw new IllegalArgumentException("JWT密钥长度必须至少32个字符");
        }
        return Keys.hmacShaKeyFor(secret.getBytes());
    }
    public String generateToken(String username) {
        return Jwts.builder()
                .subject(username)
                .issuedAt(new Date())
                .expiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(getSigningKey())
                .compact();
    }
    public String getUsernameFromToken(String token) {
        try {
            return Jwts.parser()
                    .verifyWith(getSigningKey())
                    .build()
                    .parseSignedClaims(token)
                    .getPayload()
                    .getSubject();
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("Token已过期");
        } catch (JwtException e) {
            throw new RuntimeException("Token无效: " + e.getMessage());
        }
    }
    public boolean validateToken(String token, String username) {
        try {
            String tokenUsername = getUsernameFromToken(token);

            // 验证用户名匹配且Token未过期
            Claims claims = Jwts.parser()
                    .verifyWith(getSigningKey())
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();

            Date expiration = claims.getExpiration();
            boolean isExpired = expiration.before(new Date());

            return tokenUsername.equals(username) && !isExpired;
        } catch (Exception e) {
            return false;
        }
    }
}